import _ from 'lodash';

export const hasChildren = (list, item) => {
  let result = false;
  list.forEach(value => {
    if (value.pid === item.id) {
      result = true;
    }
  });
  return result;
};

export const findById = (list, id) => {
  let result = null;
  list.forEach(value => {
    if (value.id === id) {
      result = value;
    }
  });
  return result;
};

export const buildSearchPath = (listx, pid = '0', pnode = null) => {
  let list = [];
  listx.forEach(value => {
    const x = value;
    if (`${x.pid}` === pid) {
      let name1 = value.name ? value.name : '';
      const name2 = value.freeTypeName ? value.freeTypeName : '';
      if (value.type === 'org_house_package') {
        name1 = value.areaPart;
      }
      if (value.type === 'org_salingparking') {
        name1 = '可售车位';
      }
      if (value.type === 'org_sale_parking') {
        name1 = '已售车位';
      }
      if (value.type === 'org_not_sale_parking') {
        name1 = '已定价未售车位';
      }
      if (value.type === 'org_forsaleparking') {
        name1 = '未推售车位';
      }
      x.searchPath = pnode && pnode.searchPath ? `${pnode.searchPath}${name1}/` : `/${name1}/`;
      x.searchKeys = [name1, name2];
      x.parentPaths =
        pnode && pnode.parentPaths ? _.concat(pnode.parentPaths, [pnode.searchPath]) : [];
      if (hasChildren(listx, x)) {
        list = _.union(list, buildSearchPath(listx, x.id, x));
      }
      list.push(x);
    }
  });
  return list;
};

export const buildTree = (list, pid = '0') => {
  const tree = [];
  list.forEach(value => {
    if (value.pid === pid) {
      if (hasChildren(list, value)) {
        value.children = [];
        value.children = buildTree(list, value.id);
      }
      tree.push(value);
    }
  });
  return tree;
};

// 构造每行数据方便计算
export const generateRowStructure = (list, params) => {
  const result = [];
  list.forEach(element => {
    // 是楼栋 可编辑均价 可拆分 是否必须拆完
    // 是面积段 可编辑面积、套数 可编辑均价 可删除

    // 是车位父节点 可编辑均价 可拆分  是否必须拆完
    // 是车位叶子节点 可编辑车位数 可编辑均价 可删除
    const rowData = { ...element };
    rowData.errorSplitNum = false;
    rowData.errorSplitSaleArea = false;
    rowData.errorPrice = false;
    rowData.errorNum = false;
    rowData.errorSaleArea = false;
    rowData.errorAreaSegment = false;
    rowData.isAllCollections = false;
    rowData.hasCollections = false;

    rowData.orderLeaf = 1;
    rowData.isHouseParent = false;
    rowData.canEditPrice = false;
    rowData.needEditPrice = false;
    rowData.canSplit = false;
    rowData.mustSplit = false;
    rowData.isHouseLeaf = false;
    rowData.canEditOther = false;
    rowData.canRemove = false;
    rowData.isParkingParent = false;
    rowData.isParkingLeaf = false;

    rowData.isParking = _.toNumber(rowData.isParking);
    rowData.isSplit = _.toNumber(rowData.isSplit);
    // rowData.averagePrice = _.toNumber(rowData.averagePrice);
    rowData.num = _.toNumber(rowData.num);
    rowData.num_house = _.toNumber(rowData.num_house);
    rowData.num_parking = _.toNumber(rowData.num_parking);
    rowData.num_parking_forsale = _.toNumber(rowData.num_parking_forsale);

    rowData.saleArea = _.toNumber(rowData.saleArea);
    rowData.averagePrice_house = _.toNumber(
      rowData.averagePrice_house ? rowData.averagePrice_house : 0,
    );
    rowData.averagePrice_parking = _.toNumber(
      rowData.averagePrice_parking ? rowData.averagePrice_parking : 0,
    );
    // rowData.isSupply = _.toNumber(rowData.isSupply);
    // rowData.averagePrice_house = null;
    // rowData.averagePrice_parking = null;
    // rowData.num_house = null;
    rowData.sum_house = null;
    rowData.sum_parking_saling = null;
    rowData.sum_parking_forsale = null;
    rowData.hasCollections = false;
    rowData.isAllCollections = false;
    rowData.hasSaleParking = false;

    if (
      rowData.type === 'org_salingparking' ||
      rowData.type === 'org_forsaleparking' ||
      rowData.type === 'org_sale_parking' ||
      rowData.type === 'org_not_sale_parking'
    ) {
      rowData.orderType = 1;
      rowData.isParking = 1;
      rowData.orderLeaf = rowData.type === 'org_forsaleparking' ? 999 : 0;
      // 面积段车位 只有我这边拆出来的 org_salingparking 可以编辑 可删除
      rowData.isHouseParent = false;
      rowData.canEditPrice = rowData.type === 'org_salingparking';
      rowData.needEditPrice = rowData.type === 'org_salingparking';
      // 是车位叶子节点 需要变成编辑框
      // rowData.needEditPrice = params.category !== 'strategy';
      rowData.canSplit = false;
      rowData.mustSplit = false;
      rowData.isHouseLeaf = false;
      rowData.canEditOther = rowData.type === 'org_salingparking';
      // rowData.canRemove = rowData.type === 'org_salingparking';
      rowData.isParkingParent = false;
      rowData.isParkingLeaf = true;

      rowData.saleArea = null;
      rowData.averagePrice_house = null;
      rowData.averagePrice = rowData.averagePrice_parking;
      rowData.num_house = null;
      // rowData.num_parking = rowData.num;
      rowData.sum_house = null;

      const sumParking = _.round(
        _.toNumber(rowData.num_parking) * _.toNumber(rowData.averagePrice_parking),
      );
      if (rowData.type === 'org_forsaleparking') {
        rowData.sum_parking_saling = 0;
        rowData.sum_parking_forsale = sumParking;
      } else {
        rowData.sum_parking_saling = sumParking;
        rowData.sum_parking_forsale = 0;
      }
      const parentNode = _.filter(list, item => item.id === rowData.pid);

      if (
        !(
          !parentNode.businessTypeName ||
          parentNode.businessTypeName === '可售' ||
          parentNode.businessTypeName === '阶段性自持'
        )
      ) {
        rowData.canEditOther = false;
        rowData.canRemove = false;
        rowData.canSplit = false;
        rowData.mustSplit = false;
        rowData.canEditPrice = false;
        rowData.needEditPrice = false;
      }
    }

    if (rowData.type === 'org_house_package' && rowData.isParking !== 1) {
      // 房屋面积段
      rowData.orderType = 2;
      rowData.isHouseParent = false;
      rowData.canSplit = false;
      rowData.mustSplit = false;
      rowData.isHouseLeaf = true;
      rowData.isParkingParent = false;
      rowData.isParkingLeaf = false;
      rowData.canEditPrice = false;
      rowData.canEditOther = false;
      rowData.canRemove = false;
      rowData.needEditPrice = params.category !== 'strategy';

      if (rowData.name === '其它') {
        rowData.orderLeaf = 999;
        if (!params.isMarketing) {
          // 非营销操盘拆出来的（其它）面积段可编辑价格
          rowData.canEditPrice = true;
        } else {
          rowData.canEditPrice = false;
        }
      } else {
        // 归集出来的面积段 不可删  不可编辑
        rowData.canEditPrice = rowData.isSplit !== 1;
        rowData.canEditOther = rowData.isSplit !== 1;
        rowData.canRemove = rowData.isSplit !== 1;
      }

      rowData.averagePrice = rowData.averagePrice_house;
      rowData.averagePrice_parking = null;
      // rowData.num_house = rowData.num;
      rowData.num_parking = null;
      rowData.sum_house = _.round(rowData.saleArea * rowData.averagePrice_house, 4);
      rowData.sum_parking_saling = null;
      rowData.sum_parking_forsale = null;
    }

    if (rowData.type === 'org_build' && rowData.isParking !== 1) {
      rowData.orderType = 4;
      rowData.isHouseParent = true;
      rowData.isParkingParent = false;
      rowData.isParkingLeaf = false;
      rowData.isHouseLeaf = false;
      // 在战规版出现编辑均价输入框
      rowData.needEditPrice = params.category === 'strategy';
      // 有归集  不能编辑
      const items1 = _.filter(
        list,
        item => item.pid === rowData.id && !item.isDeleted && item.isSplit === 1,
      );

      if (items1 && items1.length > 0) {
        // rowData.needEditPrice = false;
        rowData.hasCollections = true;
      }

      // 无归集 && 非营销操盘 可编辑
      if (items1.length === 0 && !params.isMarketing) {
        // rowData.needEditPrice = true;
      }
      rowData.canEditPrice = true;
      //  动态判断下面有没有其它   cansplit = child 面积和、车位数和 跟父级的比对  下面一个步骤判断了
      rowData.canSplit = false;
      // 营销操盘必须拆完
      rowData.mustSplit = params.isMarketing;

      rowData.canEditOther = false;
      rowData.canRemove = false;

      // rowData.saleArea = null;
      rowData.averagePrice = rowData.averagePrice_house;
      rowData.averagePrice_parking = null;
      // rowData.num_house = rowData.num;
      rowData.num_parking = null;
      rowData.sum_parking_saling = null;
      rowData.sum_house = _.round(rowData.saleArea * rowData.averagePrice_house, 4);
      rowData.sum_parking_forsale = null;
    }

    if (
      rowData.type === (params.category === 'investment' ? 'org_product' : 'org_build') &&
      rowData.isParking === 1
    ) {
      rowData.orderType = 5;
      // 车位楼栋
      rowData.isHouseParent = false;
      // 投资版可编辑均价
      rowData.canEditPrice = true;
      rowData.needEditPrice = true;
      // rowData.canEditPrice = params.category === 'investment' || params.category === 'strategy';
      //  动态判断下面有没有其它 下面一个步骤判断了
      const childrens = _.filter(
        list,
        item =>
          item.pid === rowData.id && item.type === 'org_salingparking' && item.isDeleted !== true,
      );
      rowData.canSplit = false;
      rowData.hasSaleParking = childrens && childrens.length > 0;
      rowData.mustSplit = false;
      rowData.isHouseLeaf = false;
      rowData.canEditOther = false;
      rowData.canRemove = false;
      rowData.isParkingParent = true;
      rowData.isParkingLeaf = false;

      rowData.saleArea = null;
      rowData.averagePrice_house = null;
      rowData.averagePrice = rowData.averagePrice_house;
      rowData.num_house = null;
      // rowData.num_parking = rowData.num;
      rowData.sum_house = null;
      rowData.sum_parking_saling = _.round(rowData.num_parking * rowData.averagePrice_parking, 4);
      rowData.sum_parking_forsale = 0;
    }

    if (
      params.category === 'investment' &&
      rowData.type === 'org_product' &&
      rowData.isParking !== 1
    ) {
      rowData.orderType = 6;
      // 投资版 业态 编辑均价
      rowData.isHouseParent = false;
      rowData.canEditPrice = true;
      rowData.needEditPrice = true;
      rowData.canSplit = false;
      rowData.mustSplit = false;
      rowData.isHouseLeaf = false;
      rowData.canEditOther = false;
      rowData.canRemove = false;
      rowData.isParkingParent = false;
      rowData.isParkingLeaf = false;

      rowData.averagePrice = rowData.averagePrice_house;
      rowData.averagePrice_parking = null;
      // rowData.num_house = rowData.num;
      rowData.num_parking = null;
      rowData.sum_house = _.round(rowData.saleArea * rowData.averagePrice_house, 4);
      rowData.sum_parking_saling = 0;
      rowData.sum_parking_forsale = 0;
    }
    if (
      !(
        !rowData.businessTypeName ||
        rowData.businessTypeName === '可售' ||
        rowData.businessTypeName === '阶段性自持'
      )
    ) {
      rowData.canEditOther = false;
      rowData.needEditPrice = false;
      rowData.canRemove = false;
      rowData.canSplit = false;
      rowData.mustSplit = false;
      rowData.canEditPrice = false;
    }

    result.push(rowData);
  });
  return _.orderBy(result, ['orderType'], ['desc']);
};

// 重新计算 其它 未推售
export const recalculateParentNodes = (listx, params) => {
  const all = [];
  const list = _.orderBy(listx, ['orderType'], ['desc']);

  list.forEach(element => {
    const node = element;
    if (element.isHouseParent) {
      if (!params.isMarketing) {
        node.mustSplit = false;
        node.canSplit = false;
        if (!element.hasCollections) {
          node.needEditPrice = true;
        }
      } else {
        // 营销操盘
        node.needEditPrice = params.category === 'strategy';
      }
      // 累计子级 非其它的面积段+套数和
      const children = _.filter(
        list,
        item =>
          item.isHouseLeaf && item.pid === element.id && item.name !== '其它' && !item.isDeleted,
      );
      children.forEach((_item, index) => {
        children[index].needEditPrice = !node.needEditPrice;
      });
      if (children && children.length > 0) {
        const sumData = _.reduce(
          children,
          (sum, item) => {
            const saleAreaSum = _.round(sum.saleArea + (item.saleArea ? item.saleArea : 0), 4);
            const numHouse = _.round(sum.num_house + (item.num_house ? item.num_house : 0), 4);
            return {
              num_house: numHouse,
              saleArea: saleAreaSum,
            };
          },
          {
            num_house: 0,
            saleArea: 0,
          },
        );

        // 比较差值 判断是否需要其它
        if (element.num_house !== sumData.num_house || element.saleArea !== sumData.saleArea) {
          node.canSplit = true;
          const fookOthers = _.filter(
            list,
            item =>
              item.isHouseLeaf &&
              item.pid === element.id &&
              item.name === '其它' &&
              item.isDeleted !== true,
          );

          const numHouse = _.round(node.num_house - sumData.num_house);
          const saleArea = _.round(node.saleArea - sumData.saleArea, 4);

          if (fookOthers && fookOthers.length > 0) {
            const fookOther = fookOthers[0];
            fookOther.xmm = '延续旧的';
            fookOther.needEditPrice = !params.isMarketing;
            fookOther.errorNum = numHouse < 0;
            fookOther.errorSaleArea = saleArea < 0;
            fookOther.num_house = numHouse;
            // fookOther.num_house = numHouse > 0 ? numHouse : 0;
            fookOther.saleArea = saleArea;
            // fookOther.saleArea = saleArea > 0 ? saleArea : 0;
            fookOther.sum_house = _.round(fookOther.saleArea * fookOther.averagePrice_house, 4);
          } else {
            // 增加其它
            const rowData = {};
            rowData.xmm = '新增的';
            rowData.type = 'org_house_package';
            rowData.isHouseParent = false;
            rowData.canSplit = false;
            rowData.mustSplit = false;
            rowData.isHouseLeaf = true;
            rowData.isParkingParent = false;
            rowData.isParkingLeaf = false;
            rowData.canEditPrice = false;
            rowData.canEditOther = false;
            rowData.canRemove = false;
            rowData.isNew = true;
            rowData.name = '其它';
            rowData.areaPart = '其它';
            rowData.needEditPrice = !params.isMarketing;
            if (!params.isMarketing) {
              // 非营销操盘拆出来的（其它）面积段可编辑价格
              rowData.canEditPrice = true;
            } else {
              rowData.canEditPrice = false;
            }

            rowData.averagePrice = 0;
            rowData.averagePrice_house = 0;
            rowData.averagePrice_parking = null;
            rowData.errorNum = numHouse < 0;
            rowData.errorSaleArea = saleArea < 0;
            rowData.num_house = numHouse;
            rowData.saleArea = saleArea;

            rowData.num_parking = null;
            rowData.sum_house = 0;
            rowData.sum_parking_saling = null;
            rowData.sum_parking_forsale = null;
            rowData.pid = node.id;
            rowData.id = `${+new Date()}${node.id}`;

            all.push(rowData);
          }
        } else {
          // 归集完了

          const fookOthers = _.filter(
            list,
            item =>
              item.isHouseLeaf &&
              item.pid === element.id &&
              item.name === '其它' &&
              !item.isDeleted,
          );
          if (fookOthers && fookOthers.length > 0) {
            fookOthers.forEach((_item, i) => {
              fookOthers[i].isDeleted = true;
            });
          }
          node.canSplit = false;
          // node.canEditPrice = false;
        }
      } else {
        // 没有面积段
        // 删除其它
        const fookOthers = _.filter(
          list,
          item =>
            item.isHouseLeaf && item.pid === element.id && item.name === '其它' && !item.isDeleted,
        );
        if (fookOthers && fookOthers.length > 0) {
          fookOthers.forEach((_item, i) => {
            fookOthers[i].isDeleted = true;
          });
        }
        if (element.num_house !== 0 || element.saleArea !== 0) {
          // 没有子集 and 没拆完 canSplit=true
          node.canSplit = true;
        }
      }
      if (!params.isMarketing) {
        node.mustSplit = false;
        node.canSplit = false;
        if (!element.hasCollections) {
          node.needEditPrice = true;
        }
      }
      // 其它算出来之后  重新计算楼栋均价
      const childrenx = _.filter(
        list,
        item =>
          item.isHouseLeaf &&
          item.pid === element.id &&
          item.averagePrice_house > 0 &&
          !item.isDeleted,
      );
      if (childrenx && childrenx.length > 0) {
        const sumData = _.reduce(
          childrenx,
          (sum, item) => {
            const saleAreaSum = _.round(sum.saleArea + (item.saleArea ? item.saleArea : 0), 4);
            const sumHouse = _.round(sum.sum_house + (item.sum_house ? item.sum_house : 0), 4);
            return {
              sum_house: sumHouse,
              saleArea: saleAreaSum,
            };
          },
          {
            sum_house: 0,
            saleArea: 0,
          },
        );
        const averagePrice = _.round(
          sumData.saleArea > 0 ? sumData.sum_house / sumData.saleArea : 0,
          4,
        );
        if (averagePrice > 0) {
          node.averagePrice = averagePrice;
          node.averagePrice_house = averagePrice;
        }
      }
    }
    // 车位楼栋
    if (element.isParkingParent) {
      // 累计子级 非其它的车位数
      // children 除为推售车位以外的车位
      const children = _.filter(
        list,
        item =>
          item.isParkingLeaf &&
          item.pid === element.id &&
          item.type !== 'org_forsaleparking' &&
          !item.isDeleted,
      );

      if (children && children.length > 0) {
        const sumData = _.reduce(
          children,
          (sum, item) => {
            const numParking = _.round(sum.num_parking + (item.num_parking ? item.num_parking : 0));
            const sumParkingSaling = _.round(
              sum.sum_parking_saling + (item.sum_parking_saling ? item.sum_parking_saling : 0),
              4,
            );
            return {
              num_parking: numParking,
              sum_parking_saling: sumParkingSaling,
            };
          },
          {
            num_parking: 0,
            sum_parking_saling: 0,
          },
        );
        const averagePrice = _.round(
          sumData.num_parking > 0 ? sumData.sum_parking_saling / sumData.num_parking : 0,
          4,
        );
        node.num_parking = sumData.num_parking;
        node.num_parking_forsale = _.round(node.num - node.num_parking);
        if (averagePrice >= 0) {
          node.averagePrice = averagePrice;
          node.averagePrice_parking = averagePrice;
        }
        node.needEditPrice = false;
        const fookOthers = _.filter(
          list,
          item =>
            item.isParkingLeaf &&
            item.pid === element.id &&
            item.type === 'org_forsaleparking' &&
            !item.isDeleted,
        );

        // 比较差值 判断是否需要其它
        // if (element.num_parking !== sumData.num_parking) {
        if (node.num - sumData.num_parking > 0) {
          if (!node.hasSaleParking) {
            node.canSplit = true;
          } else {
            node.canSplit = false;
          }

          const numParkingForsale = node.num_parking_forsale;
          // console.log('车位楼栋', element)
          // console.log('未推售车位', fookOthers)
          // console.log('非未推售车位集合', children)
          // 车位楼栋除未推售以外的车位数量
          const normalParkingNumber = children.length;
          if (fookOthers && fookOthers.length > 0) {
            const fookOther = fookOthers[0];
            // children只存在一个可售车位并且可售车位车位数为0，参考均价以可售车位均价来
            if (
              normalParkingNumber === 1 &&
              _.filter(children, { type: 'org_salingparking' }).length === 1 &&
              children[0].num_parking === 0
            ) {
              fookOther.averagePrice = children[0].averagePrice;
              fookOther.averagePrice_parking = children[0].averagePrice_parking;
            } else {
              fookOther.averagePrice = element.averagePrice;
              fookOther.averagePrice_parking = element.averagePrice_parking;
            }

            fookOther.num = numParkingForsale > 0 ? numParkingForsale : 0;
            fookOther.num_parking = 0;
            fookOther.num_parking_forsale = fookOther.num;
            fookOther.sum_parking_forsale = _.round(
              fookOther.num_parking_forsale * fookOther.averagePrice_parking,
              4,
            );
            fookOther.num_parking = 0;
            fookOther.pid = node.id;

            // 父节点剩余多少未拆分完 校验用
          } else {
            // 增加其它
            const rowData = {};
            rowData.type = 'org_forsaleparking';
            rowData.isHouseParent = false;
            rowData.canSplit = false;
            rowData.mustSplit = false;
            rowData.isHouseLeaf = false;
            rowData.isParkingParent = false;
            rowData.isParkingLeaf = true;
            rowData.canEditPrice = false;
            rowData.canEditOther = false;
            rowData.canRemove = false;
            rowData.isNew = true;
            rowData.name = '未推售车位';
            // children只存在一个可售车位并且可售车位车位数为0，参考均价以可售车位均价来
            if (
              normalParkingNumber === 1 &&
              _.filter(children, { type: 'org_salingparking' }).length === 1 &&
              children[0].num_parking === 0
            ) {
              rowData.averagePrice = children[0].averagePrice;
              rowData.averagePrice_parking = children[0].averagePrice_parking;
            } else {
              rowData.averagePrice = node.averagePrice;
              rowData.averagePrice_parking = node.averagePrice_parking;
            }
            rowData.averagePrice_house = null;
            rowData.num = numParkingForsale > 0 ? numParkingForsale : 0;
            rowData.num_parking = 0;
            rowData.num_parking_forsale = numParkingForsale > 0 ? numParkingForsale : 0;
            rowData.sum_house = null;
            rowData.sum_parking_saling = null;
            rowData.sum_parking_forsale = _.round(
              rowData.num_parking * rowData.averagePrice_parking,
              4,
            );
            rowData.pid = node.id;
            rowData.id = `${+new Date()}${node.id}`;
            all.push(rowData);
          }
        } else if (fookOthers && fookOthers.length > 0) {
          const fookOther = fookOthers[0];
          fookOther.isDeleted = true;
          fookOther.averagePrice = element.averagePrice;
          fookOther.averagePrice_parking = element.averagePrice_parking;
          fookOther.num = 0;
          fookOther.num_parking = 0;
          fookOther.num_parking_forsale = 0;
          fookOther.sum_parking_forsale = 0;
          // 父节点剩余多少未拆分完 校验用
        }
      } else {
        node.needEditPrice = true;
        node.num_parking_forsale = node.num;
        node.num_parking = 0;

        const fookOthers = _.filter(
          list,
          item =>
            item.isParkingLeaf &&
            item.pid === element.id &&
            item.type === 'org_forsaleparking' &&
            !item.isDeleted,
        );

        if (fookOthers && fookOthers.length > 0) {
          fookOthers.forEach((_item, i) => {
            fookOthers[i].isDeleted = true;
          });
        }
        if (element.num_parking_forsale > 0) {
          node.canSplit = true;
        }
      }
    }

    if (
      !(
        !element.businessTypeName ||
        element.businessTypeName === '可售' ||
        element.businessTypeName === '阶段性自持'
      )
    ) {
      node.canEditOther = false;
      node.canRemove = false;
      node.canSplit = false;
      node.mustSplit = false;
      node.canEditPrice = false;
      node.needEditPrice = false;
    }
    all.push(node);
  });
  return all;
};

export const calculateValidateOptions = (list, params) => {
  list.forEach(element => {
    const node = element;
    if (params.category === 'investment' && node.type === 'org_product' && node.isParking !== 1) {
      if (node.canEditPrice && node.averagePrice_house <= 0) {
        node.errorPrice = true;
      }
    }

    if (
      !params.isMarketing &&
      node.type === 'org_house_package' &&
      node.name === '其它' &&
      !node.isDeleted
    ) {
      if (node.canEditPrice && node.averagePrice_house <= 0) {
        node.errorPrice = true;
      }
    }

    if (element.isHouseLeaf) {
      if (element.canEditOther && element.left_saleArea < 0) {
        element.errorSaleArea = true;
      }
      if (element.canEditOther && element.saleArea <= 0) {
        element.errorSaleArea = true;
      }
      if (element.canEditOther && element.num_house <= 0) {
        element.errorNum = true;
      }
      if (element.canEditOther && element.left_num_house < 0) {
        element.errorNum = true;
      }
    }
    if (element.isHouseParent) {
      if (element.canEditPrice && element.averagePrice_house <= 0) {
        node.errorPrice = true;
      }
      // 父节点剩余多少未拆分完 校验用
      const childrenOrthers = _.filter(
        list,
        item => item.pid === node.id && item.name === '其它' && !item.isDeleted,
      );
      const childrenxx = _.filter(
        list,
        item => item.isHouseLeaf && item.pid === node.id && item.name !== '其它' && !item.isDeleted,
      );

      if (childrenOrthers && childrenOrthers.length > 0) {
        const childrenOrther = childrenOrthers[0];
        node.left_num_house = childrenOrther.num_house;
        node.left_saleArea = childrenOrther.saleArea;
      } else {
        if (element.hasCollections) {
          node.isAllCollections = true;
          if (childrenxx && childrenxx.length > 0) {
            childrenxx.forEach(elementx => {
              if (elementx.isSplit != 1) {
                node.isAllCollections = false;
              }
            });
          }
          if (node.isAllCollections) {
            node.canEditPrice = false;
          }
        }
        if (childrenxx && childrenxx.length > 0) {
          node.left_num_house = 0;
          node.left_saleArea = 0;
        } else {
          node.left_num_house = node.num_house;
          node.left_saleArea = node.saleArea;
        }
      }
      if (node.mustSplit) {
        if (node.left_num_house !== 0) {
          node.errorSplitNum = true;
        }
        if (node.left_saleArea !== 0) {
          node.errorSplitSaleArea = true;
        }
      }

      if (childrenxx && childrenxx.length > 0) {
        childrenxx.forEach((child, index) => {
          if (child.canEditPrice && child.averagePrice_house <= 0) {
            childrenxx[index].errorPrice = true;
          }
          if (child.canEditOther && child.saleArea <= 0) {
            childrenxx[index].errorSaleArea = true;
          }
          // if (child.canEditOther && child.num_house <= 0) {
          //   childrenxx[index].errorNum = true;
          // }
          if (
            child.canEditOther &&
            (!!child.areaPart === false || child.areaPart === '请选择面积段')
          ) {
            childrenxx[index].errorAreaSegment = true;
          }
          childrenxx[index].left_num_house = node.left_num_house;
          childrenxx[index].left_saleArea = node.left_saleArea;
        });
      }
    }
    if (element.isParkingParent) {
      // 父节点剩余多少未拆分完 校验用
      // const childrenOrthers = _.filter(
      //   list,
      //   item =>
      //     item.isParkingLeaf &&
      //     item.pid === element.id &&
      //     item.type === 'org_forsaleparking' &&
      //     !item.isDeleted,
      // );
      const childrenxx = _.filter(
        list,
        item =>
          item.isParkingLeaf &&
          item.pid === element.id &&
          item.type !== 'org_forsaleparking' &&
          !item.isDeleted,
      );
      node.num_parking_forsale = _.round(node.num - node.num_parking);
      node.left_num_parking = node.num_parking_forsale;
      // if (childrenOrthers && childrenOrthers.length > 0) {
      //   const childrenOrther = childrenOrthers[0];
      //   node.left_num_parking = childrenOrther.num_parking_forsale;
      // } else if (childrenxx && childrenxx.length > 0) {
      //   node.left_num_parking = 0;
      // } else {
      //   node.left_num_parking = node.num_parking_forsale;
      // }
      let conditions = false;
      // 当车位数目>0 均价要>0
      if (node.num_parking > 0) {
        conditions = node.averagePrice_parking <= 0;
      } else {
        conditions = node.averagePrice_parking < 0;
      }
      if (node.canEditPrice && conditions) {
        node.errorPrice = true;
      }

      if (childrenxx && childrenxx.length > 0) {
        childrenxx.forEach((child, index) => {
          conditions = false;
          if (child.num_parking > 0) {
            conditions = child.averagePrice_parking <= 0;
          } else {
            conditions = child.averagePrice_parking < 0;
          }

          if (child.canEditPrice && conditions) {
            childrenxx[index].errorPrice = true;
          }
          if (child.canEditOther && child.num_parking < 0) {
            childrenxx[index].errorNum = true;
          }
          childrenxx[index].left_num_parking = node.num_parking_forsale;
        });
      }
    }
  });
  return list;
};
export const canSave = list => {
  for (let i = 0; i < list.length; i += 1) {
    const rowData = list[i];
    if (rowData.canSplit && (rowData.errorSplitNum || rowData.errorSplitSaleArea)) {
      return false;
    }
    if (rowData.canEditPrice && rowData.errorPrice) {
      return false;
    }
    if (rowData.canEditOther && rowData.errorNum) {
      return false;
    }
    if (rowData.canEditOther && rowData.errorSaleArea) {
      return false;
    }
    if (rowData.errorAreaSegment) {
      return false;
    }
  }
  return true;
};

const calculateRowData = (data, params) => {
  let rowData = data;
  if (
    !(
      !rowData.businessTypeName ||
      rowData.businessTypeName === '可售' ||
      rowData.businessTypeName === '阶段性自持'
    )
  ) {
    return data;
  }
  if (
    rowData.isParkingLeaf ||
    rowData.isParkingParent ||
    rowData.isHouseLeaf ||
    (rowData.isHouseParent && !params.isQuery)
  ) {
    rowData.sum_house = null;
    rowData.sum_parking_saling = null;
    rowData.sum_parking_forsale = null;
    rowData.averagePrice = rowData.averagePrice_parking;
    if (rowData.isParkingLeaf) {
      if (rowData.type === 'org_forsaleparking') {
        rowData.sum_parking_forsale = _.round(
          rowData.averagePrice_parking * rowData.num_parking_forsale,
          4,
        );
      } else {
        rowData.sum_parking_saling = _.round(rowData.averagePrice_parking * rowData.num_parking, 4);
      }
    }
    if (rowData.isHouseLeaf) {
      rowData.sum_house = _.round(rowData.averagePrice_house * rowData.saleArea, 4);
    }
    if (rowData.isParkingParent || rowData.isHouseParent) {
      if (rowData.children && rowData.children.length > 0) {
        rowData.sum_house = null;
        rowData.sum_parking_saling = null;
        rowData.sum_parking_forsale = null;
        const sumData = _.reduce(
          rowData.children,
          (sum, item) => {
            const sumHouse = _.round(sum.sum_house + (item.sum_house ? item.sum_house : 0), 4);
            const sumParkingSaling = _.round(
              sum.sum_parking_saling + (item.sum_parking_saling ? item.sum_parking_saling : 0),
              4,
            );
            const sumParkingForsale = _.round(
              sum.sum_parking_forsale + (item.sum_parking_forsale ? item.sum_parking_forsale : 0),
              4,
            );
            return {
              sum_house: sumHouse,
              sum_parking_saling: sumParkingSaling,
              sum_parking_forsale: sumParkingForsale,
            };
          },
          {
            sum_house: 0,
            sum_parking_saling: 0,
            sum_parking_forsale: 0,
          },
        );
        rowData.sum_house = sumData.sum_house;
        rowData.sum_parking_saling = sumData.sum_parking_saling;
        rowData.sum_parking_forsale = sumData.sum_parking_forsale;
      } else {
        rowData.sum_parking_forsale = 0;
        rowData.sum_parking_saling = 0;
        rowData.sum_house = 0;
        if (rowData.isParkingParent) {
          rowData.sum_parking_saling = _.round(
            rowData.num_parking * rowData.averagePrice_parking,
            4,
          );
          rowData.sum_parking_forsale = _.round(
            rowData.num_parking_forsale * rowData.averagePrice_parking,
            4,
          );
        }
        if (rowData.isHouseParent) {
          rowData.sum_house = _.round(rowData.saleArea * rowData.averagePrice_house, 4);
        }
      }
    }
  } else {
    const sumData = _.reduce(
      rowData.children,
      (sum, item) => {
        if (
          !(
            !item.businessTypeName ||
            item.businessTypeName === '可售' ||
            item.businessTypeName === '阶段性自持'
          )
        ) {
          return sum;
        }
        const sumHouse = _.round(sum.sum_house + (item.sum_house ? item.sum_house : 0), 4);
        const sumParkingSaling = _.round(
          sum.sum_parking_saling + (item.sum_parking_saling ? item.sum_parking_saling : 0),
          4,
        );
        const sumParkingForsale = _.round(
          sum.sum_parking_forsale + (item.sum_parking_forsale ? item.sum_parking_forsale : 0),
          4,
        );
        const saleAreaSum = _.round(sum.saleArea + (item.saleArea ? item.saleArea : 0), 4);
        const numHouse = _.round(sum.num_house + (item.num_house ? item.num_house : 0), 4);
        const numParking = _.round(sum.num_parking + (item.num_parking ? item.num_parking : 0));
        const numParkingForsale = _.round(
          sum.num_parking_forsale + (item.num_parking_forsale ? item.num_parking_forsale : 0),
        );

        const averagePriceHouse = _.round(saleAreaSum === 0 ? 0 : sumHouse / saleAreaSum, 4);
        const averagePriceParking = _.round(
          numParking === 0 ? 0 : sumParkingSaling / numParking,
          4,
        );

        return {
          averagePrice_house: averagePriceHouse,
          averagePrice_parking: averagePriceParking,
          num_house: numHouse,
          saleArea: saleAreaSum,
          num_parking: numParking,
          num_parking_forsale: numParkingForsale,
          sum_house: sumHouse,
          sum_parking_saling: sumParkingSaling,
          sum_parking_forsale: sumParkingForsale,
        };
      },
      {
        averagePrice_house: 0,
        averagePrice_parking: 0,
        num_parking: 0,
        num_parking_forsale: 0,
        num_house: 0,
        saleArea: 0,
        sum_house: 0,
        sum_parking_saling: 0,
        sum_parking_forsale: 0,
      },
    );
    if (
      params &&
      params.category === 'investment' &&
      rowData.type === 'org_product' &&
      rowData.isParking !== 1
    ) {
      rowData = {
        ...rowData,
        sum_house: _.round(rowData.averagePrice_house * rowData.saleArea, 4),
        sum_parking_saling: null,
        sum_parking_forsale: null,
      };
    } else {
      rowData = {
        ...rowData,
        ...sumData,
      };
    }
  }

  return rowData;
};
const traverseCalculate = (items, params) => {
  const x = items.map(element => {
    let y = element;
    if (element.children && element.children.length > 0) {
      y.children = traverseCalculate(element.children, params);
    }
    y = calculateRowData(y, params);
    return y;
  });
  return x;
};
export const calculateTreeData = (treeData, params) => traverseCalculate(treeData, params);

export const getSearchItems = list => {
  // buildTree add children
  buildTree(list, '0');
  const items = {};
  let types = [];
  // 筛选出所有类型
  _(list).forEach(value => {
    types.push(value.type);
  });
  // 去重
  types = _.uniq(types);
  // 类型数组
  _(types).forEach(value => {
    items[value] = [];
  });
  // 遍历相同类型的对象插入数组
  _(list).forEach(value => {
    _(types).forEach(val => {
      if (val === value.type) {
        items[val].push(value);
      }
    });
  });

  return items;
};

export const getSearchTypeItems = (list, name, code) => {
  const data = [];
  _(list).forEach(value => {
    if (value[`${name}`] && value[`${code}`]) {
      data.push({
        name: value[`${name}`],
        code: value[`${code}`],
      });
    }
  });
  return _.uniqBy(data, 'name');
};

export const getSearchLists = list => {
  const data = [];
  _(list).forEach(value => {
    data.push({
      name: value.name,
      code: value.id,
    });
  });
  return _.uniqBy(data, 'name');
};

// 显示的select下拉框
export const getSelects = tabKey => {
  const formItems = [];
  if (tabKey === 'investment') {
    formItems.push(
      {
        id: 'productType',
        datakey: 'productTypes',
        label: '业态',
        span: 6,
      },
      {
        id: 'product',
        datakey: 'products',
        label: '产品构成',
        span: 6,
      },
      {
        id: 'decorationStandard',
        datakey: 'decorationStandards',
        label: '产品属性',
        span: 6,
      },
    );
  } else {
    formItems.push(
      {
        id: 'productType',
        datakey: 'productTypes',
        label: '业态',
        span: 5,
      },
      {
        id: 'product',
        datakey: 'products',
        label: '产品构成',
        span: 5,
      },
      {
        id: 'build',
        datakey: 'builds',
        label: '楼栋',
        span: 5,
      },
      {
        id: 'decorationStandard',
        datakey: 'decorationStandards',
        label: '产品属性',
        span: 4,
      },
      {
        id: 'area',
        datakey: 'areas',
        label: '面积段',
        span: 4,
      },
    );
  }
  return formItems;
};

export const getExpandedRowKeys = list => {
  const expandedRowKeys = [];
  _.forEach(list, value => {
    expandedRowKeys.push(value.id);
  });
  return expandedRowKeys;
};

export const filterAll = ({ all, query }) => {
  const leafNodes1 = _.filter(all, item => {
    let result = true;

    if (query.decorationStandard) {
      if (
        item.freeTypeName === query.decorationStandard ||
        item.businessTypeName === query.decorationStandard ||
        item.proTypeName === query.decorationStandard
      ) {
        result = true;
      } else {
        return false;
      }
    }

    if (query.productType) {
      if (item.proProductName === query.productType) {
        result = true;
      } else {
        return false;
      }
    }
    return result;
  });

  const leafNodes = _.filter(all, item => {
    let result = null;
    if (leafNodes1 && leafNodes1.length > 0) {
      if (_.findIndex(leafNodes1, itemx => item.searchPath.search(itemx.searchPath) > -1) > -1) {
        result = true;
      } else {
        return false;
      }
    }
    if (query.product) {
      if (item.searchPath.search(`/${query.product}/`) > -1) {
        result = true;
      } else {
        return false;
      }
    }
    if (query.area) {
      if (item.searchPath.search(`/${query.area}/`) > -1) {
        result = true;
      } else {
        return false;
      }
    }
    if (query.build) {
      if (item.searchPath.search(`/${query.build}/`) > -1) {
        result = true;
      } else {
        return false;
      }
    }
    return result;
  });
  let parentPaths = [];
  if (leafNodes && leafNodes.length > 0) {
    leafNodes.forEach(item => {
      parentPaths = _.union(parentPaths, item.parentPaths);
    });
  }
  const pNodes = _.filter(
    all,
    item => _.findIndex(parentPaths, itemx => itemx === item.searchPath) > -1,
  );
  return _.union(leafNodes, pNodes);
};

export const tree2array = tree => {
  const items = [];
  tree.forEach(element => {
    items.push({
      ...element,
      children: null,
    });
    if (element.children && element.children.length > 0) {
      const childrens = tree2array(element.children);
      if (childrens && childrens.length > 0) {
        items.push(...childrens);
      }
    }
  });
  return items;
};

export const getItemsForSave = (tree, all) => {
  // 校验
  // 把tree平铺
  // TODO 合并面积段相同的

  const list = _.cloneDeep(tree2array(tree));
  const deletedItems = _.filter(all, item => item.isDeleted);

  list.push(...deletedItems);
  const items = {};
  let types = [];
  // 筛选出所有类型
  _(list).forEach((value, _index) => {
    types.push(value.type);
  });
  // 去重
  types = _.uniq(types);
  // 类型数组
  _(types).forEach(value => {
    items[value] = [];
  });
  // 遍历相同类型的对象插入数组
  _(list).forEach((value, index) => {
    _(types).forEach(val => {
      if (val === value.type) {
        if (
          value.type === 'org_salingparking' ||
          value.type === 'org_forsaleparking' ||
          value.type === 'org_sale_parking' ||
          value.type === 'org_not_sale_parking'
        ) {
          list[index].averagePrice = value.averagePrice_parking;
          // list[index].num = value.num_parking;
        }
        if (value.type === 'org_house_package') {
          // const parentNodes = _.filter(list, item => item.id === value.pid);
          // if (parentNodes && parentNodes.length > 0) {
          //   const parentNode = parentNodes[0];
          //   if (value.name !== '其它') {
          //     list[index].isSplit = parentNode.hasCollections ? 1 : 0;
          //   }
          // }
          list[index].averagePrice = value.averagePrice_house;
          list[index].num = value.num_house;
        }
        items[val].push(value);
      }
    });
  });
  //   房源包 org_house_package
  // 可售车位 org_salingparking
  // 已售车位 org_sale_parking
  // 已定价未售车位 org_not_sale_parking
  items.org_house = [];
  // 处理相同面积段问题

  // items.org_house_package
  console.log(items.org_house_package, 'items.org_house_package');
  // debugger;
  if (items.org_house_package) {
    // 处理 有归集出来的面积段 跟刚拆的面积段 重复  需要去重重新算均价
    let collectedItems = _.filter(
      items.org_house_package,
      detail => detail.isSplit === 1 && detail.isDeleted !== true,
    );
    collectedItems = _.orderBy(collectedItems, ['id'], ['asc']);

    if (collectedItems && collectedItems.length > 0) {
      collectedItems.forEach(element => {
        const x = element;
        const foundItems = _.filter(
          items.org_house_package,
          detail => detail.pid === element.pid && detail.areaPart === element.areaPart,
        );
        // 找出多余1个 合并
        if (foundItems && foundItems.length > 1) {
          // 重新计算价格
          // 累计面积
          // 累计套数
          const sumData = _.reduce(
            foundItems,
            (sum, item) => {
              const saleAreaSum = _.round(sum.saleArea + (item.saleArea ? item.saleArea : 0), 4);
              const numHouse = _.round(sum.num_house + (item.num_house ? item.num_house : 0));
              const sumHouse = _.round(sum.sum_house + (item.sum_house ? item.sum_house : 0), 4);
              return {
                num_house: numHouse,
                saleArea: saleAreaSum,
                sum_house: sumHouse,
              };
            },
            {
              num_house: 0,
              saleArea: 0,
              sum_house: 0,
            },
          );
          x.num_house = sumData.num_house;
          x.num = sumData.num_house;
          x.saleArea = sumData.saleArea;
          x.sum_house = sumData.sum_house;
          x.averagePrice_house = _.round(x.sum_house / x.saleArea, 4);
          x.averagePrice = x.averagePrice_house;
          items.org_house.push(x);
        } else if (foundItems && foundItems.length === 1) {
          items.org_house.push(x);
        }
      });
      // const houseItems2 = _.filter(
      //   items.org_house_package,
      //   detail => detail.isSplit !== 1 || detail.isDeleted !== true,
      // );
      // if (houseItems2 && houseItems2.length > 0) {
      //   items.org_house.push(...houseItems2);
      // }
    }
    console.log(items.org_house, 'items.org_house');

    const notCollectedItems = _.filter(
      items.org_house_package,
      detail => detail.isSplit !== 1 && detail.isDeleted !== true,
    );
    // 非归集出来面积段 删除面积段重复的
    if (notCollectedItems && notCollectedItems.length > 0) {
      notCollectedItems.forEach(element => {
        const x = element;
        const foundItems = _.filter(
          items.org_house,
          detail =>
            detail.pid === element.pid &&
            detail.areaPart === element.areaPart &&
            detail.isDeleted !== true,
        );
        if (foundItems && foundItems.length > 0) {
          x.isDeleted = true;
        }
        items.org_house.push(x);
      });
    }
    console.log(items.org_house, 'items.org_house');

    const deletedHouseItems = _.filter(
      items.org_house_package,
      detail => detail.isDeleted === true,
    );
    items.org_house.push(...deletedHouseItems);
    console.log(items.org_house, 'items.org_house');

    items.org_house = _.filter(items.org_house, item => !(item.isDeleted && item.isNew));
  }
  console.log(items.org_house, 'items.org_house');
  if (items.org_forsaleparking) {
    items.org_house.push(...items.org_forsaleparking);
  }
  if (items.org_salingparking) {
    items.org_house.push(...items.org_salingparking);
  }
  if (items.org_sale_parking) {
    items.org_house.push(...items.org_sale_parking);
  }
  if (items.org_not_sale_parking) {
    items.org_house.push(...items.org_not_sale_parking);
  }
  return items;
};

// 删除其它
// 保存all
// 过滤删除的数据
// 构造每行数据方便计算
//  先构造父级 会追加出其它+未推售子节点 不计算出父级的均价（）
//  构造leaf节点
// 生成树 计算
//  除了叶子节点的均价 其它均价 套数 面积 车位数 都应该是累积重新计算的

// 编辑时
//  重新计算本行
//  重新构造父级 追加出其它+未推售子节点
//  重新生成树 计算
// 保存
//  把tree变成数组 加上delete的node 一并提交

// 搜索 构成树
//  重新生成树 计算 （搜索面积段的时候 要去掉车位相关节点）

// 构造tree
// 重新计算tree的值（面积段、可售车位等 不用重新计算均价   分两个层次 一个是叶子节点（面积段） 一个是以上）

export const buildChildren = (items, list, type) => {
  list.forEach(value => {
    if (value.type === type) {
      items.push(value);
    } else if (value.children && value.children.length) {
      buildChildren(items, value.children, type);
    }
  });
  return items;
};

export const getSearchSeltetItems = (list, type, name, id) => {
  const items = [];
  const buildItems = buildChildren(items, list, type);
  return getSearchTypeItems(buildItems, name, id);
};

export const getCalculatedTree = (all, params) => {
  let list = _.cloneDeep(_.filter(all, item => item.isDeleted !== true));
  list = _.orderBy(list, ['orderLeaf'], ['asc']);
  const tree = buildTree(list, '0');
  return calculateTreeData(tree, params);
};

/* 判断对象里面是否都为空 */
export const isObjectEmpty = object => {
  let isEmpty = true;
  Object.keys(object).forEach(x => {
    if (object[x] !== null && object[x] !== '' && object[x] !== undefined) {
      isEmpty = false;
    }
  });
  if (isEmpty) {
    // 值全为空
    return true;
  }
  return false;
};

// 普调批量操作弹层数据
export function getItemRows(tree, parentName = '', arrData = []) {
  tree.forEach(item => {
    const canEdit = item.needEditPrice && (item.name === '其它' || item.canEditPrice);
    // 拼接name名称---begin
    const setItem = _.cloneDeep(item);
    setItem.namePath = parentName;
    if (
      [
        'org_group',
        'org_product',
        'org_build',
        // 'org_house_package',
        // 'org_parking_package',
      ].includes(item.type)
    ) {
      setItem.namePath += `${parentName === '' ? '' : '-'}${item.name}`;
    }
    // 拼接name名称---end
    if (canEdit) {
      // 已知调整前均价 已知调整后均价 幅度 (调整后 - 调整前) / 调整前
      // 计算调整幅度
      const beforePrice = item.isParking
        ? Number(item.averagePrice_parking_init).toFixed(0)
        : Number(item.averagePrice_house_init).toFixed(0);
      const afterPrice = item.isParking ? item.averagePrice_parking : item.averagePrice_house;

      const range = ((afterPrice - beforePrice) / beforePrice) * 100;

      arrData.push({
        id: item.id,
        name: setItem.namePath,
        orgPackage: [
          'org_house_package',
          'org_parking_package',
          'org_sale_parking',
          'org_not_sale_parking',
          'org_forsaleparking',
          'org_salingparking',
        ].includes(item.type)
          ? item?.name
          : '',
        beforePrice,
        afterPrice,
        range: _.isNaN(range) ? 0 : range,
        rows: item,
      });
    }
    if (!_.isEmpty(item.children)) {
      getItemRows(item.children, setItem.namePath, arrData);
    }
  });
  return arrData;
}
